package face.pay.system.filter;

import face.pay.system.SessionUtils;
import face.pay.entity.UserInfo;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Auther: zkj
 * @Date: 2019/7/11 16:19
 * @Description:
 */
@Slf4j
@WebFilter(filterName = "login", urlPatterns = "/*")
public class LoginFilter implements Filter {

    private String[] pass_url=new String[]{"/do_login","/login","/favicon.ico","/forGet/toPage","/forGet/restPassword"};

    private String[] static_file=new String[]{"/js","/image","/css","/jquery","/sui","/zepto","/util"};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest)servletRequest;

        HttpServletResponse response = (HttpServletResponse)servletResponse;

        String url =request.getRequestURI();

        log.info("请求地址:"+url);

        if(!isPass(url)){

            UserInfo loginUser = SessionUtils.getUserFromSession(request);
            if(loginUser==null){
                response.sendRedirect("/login");
                return;
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }


    public Boolean isPass(String url){

        for(String u : pass_url){
            if(url.equals(u)){
                return true;
            }
        }

        for(String u : static_file){
            if(url.startsWith(u)){
                return true;
            }
        }

        return  false;

    }

    @Override
    public void destroy() {

    }
}
